#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#
# Copyright(c) http://m.ecpark.cn/
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import hashlib
import logging
import os

log = logging.getLogger(__name__)

formatter = logging.basicConfig(
    level=logging.DEBUG,
    format=
    '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%a, %d %b %Y %H:%M:%S')


def get_file_size(file):
    try:
        file_size = os.path.getsize(file)
        return file_size
    except FileNotFoundError as e:
        log.exception(str(e))
        return 0


def get_file_last_modified_time(file):
    try:
        modified_time = os.path.getmtime(file)
        return modified_time
    except FileNotFoundError as e:
        log.exception(str(e))
        return 0


def get_file_last_line(file_name):
    """
    拿文件最后一行
    :param file_name:
    :return:
    """
    try:
        with open(file_name, "rb") as f:
            f.seek(-2, os.SEEK_END)  # Jump to the second last byte.
            while f.read(1) != b"\n":  # Until EOL is found...
                # ...jump back the read byte plus one more.
                f.seek(-2, os.SEEK_CUR)
            last = f.readline()  # Read last line.
            return last.decode("utf-8")
    except FileNotFoundError as e:
        log.exception(str(e))
        return ""
    except Exception as e:
        log.exception(str(e))
        return ""


def judge_backup_log_file_ok(last_line, end_string="completed OK!\n"):
    """
    判断文件末尾是否符合要求
    :param last_line:
    :param end_string:
    :return:
    """
    try:
        if last_line.endswith(end_string):
            return 1
        else:
            return 0
    except AttributeError as e:
        log.exception(str(e))
        return 0


def file_md5_calc(f_name):
    """
    计算文件md5值
    :param f_name:
    :return:
    """
    try:
        hash_md5 = hashlib.md5()
        with open(f_name, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
    except Exception as e:
        return ''
    return hash_md5.hexdigest()


def get_xtrabackup_command(xtrabackup_path='./xtrabackup/bin',
                           xtrabackup_command_name='innobackupex'):
    file_full_path = '{xtrabackup_path}/{xtrabackup_command_name}'.format(
        xtrabackup_path=xtrabackup_path,
        xtrabackup_command_name=xtrabackup_command_name)
    try:
        if os.path.exists(file_full_path):
            return file_full_path
        else:
            return xtrabackup_command_name
    except Exception:
        return xtrabackup_command_name


def make_dir(path_to_make):
    try:
        if not os.path.exists(path_to_make):
            os.makedirs(path_to_make)
    except Exception as e:
        log.exception(str(e))
